<template>
  <div class="tools-div">
    <el-button type="success" size="small" @click="addShow">添加一级节点</el-button>
    <el-button type="success" size="small" plain @click="importData">从Excel导入</el-button>
    <el-button type="primary" size="small" plain @click="exportDate">导出Excel</el-button>
  </div>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%" :before-close="cancelOperate">
    <el-form label-width="120px">
      <el-form-item label="分类名称">
        <el-input v-model.trim="category.name" />
      </el-form-item>
      <el-form-item label="图标">
        <UploadImage :image-url="category.imageUrl" :old-files="oldFiles" @uploadSuccess="handleUploadSuccess"  />
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model.number="category.orderNum" />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="category.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate">提交</el-button>
        <el-button @click="cancelOperate">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-table
    :data="list"
    style="width: 100%; margin-bottom: 20px"
    row-key="id"
    border
  >
    <el-table-column prop="name" label="分类名称" />
    <el-table-column prop="imageUrl" label="图标" #default="scope" align="center" width="100">
      <img v-if="scope.row.imageUrl" :src="scope.row.imageUrl" alt="分类图标" class="category_icon">
      <span v-else>...</span>
    </el-table-column>
    <el-table-column prop="orderNum" label="排序" align="center" width="100" />
    <el-table-column prop="status" label="状态" #default="scope" align="center" width="100">
      <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
      <el-tag v-else type="danger">停用</el-tag>
    </el-table-column>
    <el-table-column label="操作" align="center" width="280" #default="scope">
      <el-button type="success" size="small" @click="addShow(scope.row)">
        添加下级节点
      </el-button>
      <el-button type="primary" size="small" @click="editShow(scope.row)">
        修改
      </el-button>
      <el-button type="danger" size="small" @click="removeCategory(scope.row)">
        删除
      </el-button>
    </el-table-column>
  </el-table>
<!--  Excel导入-->
  <el-dialog v-model="dialogImportVisible" title="导入Excel" width="30%">
    <el-form label-width="120px">
      <el-form-item label="分类文件">
        <el-upload
          class="upload-demo"
          :action="`${BASE_URL}/admin/product/category/import-data`"
          :on-success="onUploadExcelSuccess"
          :before-upload="beforeUploadExcel"
        >
          <el-button type="primary">上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import CategoryApi from "@/api/product/category";
import FileApi from "@/api/product/file";
import { ElMessage, ElMessageBox } from "element-plus";
import { useProduct } from "@/pinia/modules/product";
import { BASE_URL } from "@/utils/request";
import { deepClone } from "@/utils/index";
import UploadImage from "@/components/UploadImage/uploadImage.vue";

const appStore = useProduct();

// 定义表格数据模型
const list = ref([]);

// 定义添加表单分类表单相关数据模型
const dialogTitle = ref("添加 / 修改");
const dialogVisible = ref(false);

//页面表单数据
const defaultForm = {
  id: null,
  name: null,
  imageUrl: null,
  orderNum: 0,
  status: 1,
  oldImageUrl: null
};
// 表单响应式数据模型对象
const category = ref(defaultForm);

// 缓存已上传的图片
let oldFiles = ref([])
//=======================添加和修改功能====================
// 显示添加弹窗
const addShow = row => {
  category.value = deepClone(defaultForm);
  dialogVisible.value = true;
  if (!row.id) {
    dialogTitle.value = "添加";
  } else {
    dialogTitle.value = "添加下级节点";
    category.value.parentId = row.id;
  }
};

// 显示修改弹窗
const editShow = row => {
  //把row行数据深拷贝给 category对象做数据回显
  category.value = deepClone(row);
  category.value.oldImageUrl = row.imageUrl
  dialogVisible.value = true;
};
// 取消表单操作
const cancelOperate = () => {
  dialogVisible.value = false
  // 删除之前上传的图片
  if (oldFiles.value.length > 0) {
    FileApi.remove(oldFiles.value)
  }
  oldFiles.value = []
}

// ===================== 上传操作 ==========================
const handleUploadSuccess = imgSrc => {
  category.value.imageUrl = imgSrc;
  oldFiles.value.push(imgSrc)
};

//提交保存与修改
const saveOrUpdate = async () => {
  if (category.value.name === null || category.value.name === '') {
    return ElMessage.warning("分类名称不能为空");
  }
  if (!category.value.parentId) {
    category.value.parentId = 0;
  }
  const result = await CategoryApi.operate(category.value);
  if (result.code === 250) {
    ElMessage.success(result.message);
    await fetchData();
  } else {
    ElMessage.error(result.message);
  }
  // 删除之前上传的冗余图片
  FileApi.remove(oldFiles.value.filter(src => src !== category.value.imageUrl))
  oldFiles.value = []
  dialogVisible.value = false;
};

// 获取分类数据
const fetchData = async () => {
  const { data: result } = await CategoryApi.findAll();
  appStore.saveCategories(result);
  list.value = appStore.getCategories();
};

// 加载数据
onMounted(() => {
  // 从本地缓存拿
  const categories = appStore.getCategories();
  if (categories != null && categories.length !== 0) {
    list.value = categories;
  }
  // 本地缓存没有，请求后端
  else {
    fetchData();
  }
});

// 删除功能
const removeCategory = async row => {
  if (row.children.length !== 0) return ElMessage.warning("该分类拥有子节点，不支持删除！");
  ElMessageBox.confirm("此操作将永久删除该记录, 是否继续?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const result = await CategoryApi.removeById(row.id, row.imageUrl);
    if (result.code === 252) {
      ElMessage.success(result.message);
      await fetchData();
    } else {
      ElMessage.error(result.message);
    }
  });
};

// 导出到Excel
const exportDate = () => {
  // 调用 CategoryApi.exportData() 方法获取导出数据
  CategoryApi.exportData().then(res => {
    // 创建 Blob 对象，用于包含二进制数据
    const blob = new Blob([res]);
    // 创建 a 标签元素，并将 Blob 对象转换成 URL
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    // 设置下载文件的名称
    link.download = '分类数据.xlsx';
    // 模拟点击下载链接
    link.click();
  })
}

// 文件上传相关变量以及方法定义
const dialogImportVisible = ref(false)

// 导入excel表单渲染
const importData = () => {
  dialogImportVisible.value = true
}


// 上传excel前判断文件类型
const beforeUploadExcel = (rawFile) => {
  const suffix = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)
  const reg = /^(xlsx|xls)$/;
  if (!reg.test(suffix)) {
    ElMessage.warning("文件格式不支持！");
    return false;
  }
  return true;
}

// 上传文件成功以后要执行方法
const onUploadExcelSuccess = async (response, file) => {
  dialogImportVisible.value = false
  await CategoryApi.FindCategoryByParentId(0);
  await fetchData();
  ElMessage.success('操作成功')
}
</script>

<style scoped>
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.category_icon {
  width: 50px;
}
</style>
